package com.parcial.data.conn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class Conexion implements InterfaceConexion {

	private Connection conn;
	private String databaseName = "parcial";
	private String user = "root";
	private String password = "";
	private String host =  "127.0.0.1";//"localhost";127.0.0.1
	private String port = "3306";
	
	private static Conexion conexion;
	
	private Conexion() {		
	}
	
	public static Conexion obtenerConexion() {
		if(conexion == null) {
			conexion = new Conexion();
			conexion.open();
		}		
		return conexion;
	}

	public PreparedStatement prepareStatement(String sentenciaSQL) {
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sentenciaSQL);
		} catch (Exception e) {
			System.out.println("Error al crear el statement");
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return ps;
	}
	
	@Override
	public void commit() {
		try {
			conn.commit();
		} catch (Exception e) {
			System.out.println("Error al realizar el commit de la conexion");
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}

	@Override
	public void rollback() {
		try {
			conn.rollback();
		} catch (Exception e) {
			System.out.println("Error al realizar rollback de la conexion");
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}

	@Override
	public void open() {
		String url = "jdbc:mysql://" + host + ":" + port + "/" + databaseName;
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(url, user, password);
			conn.setAutoCommit(false);
		} catch (Exception e) {
			System.out.println("Error al crear la conexion");
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		System.out.println("Se abrio la conexion");
	}

	@Override
	public void close() {
		try {
			conn.close();
		} catch (Exception e) {
			System.out.println("Error al cerrar la conexion");
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}
	
	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		this.conn.close();
		this.conn = null;
	}
	
}
